package org.example;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

@Slf4j
public class Atomic {



    public static void main(String[] args) throws InterruptedException, ExecutionException {
        AtomicReference<Thread> waiter = new AtomicReference<>();

        new Thread(() -> {
            while (true) {
                waiter.set(Thread.currentThread());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {

                }
                System.out.println("ddd");
            }

        }).start();

        Thread.sleep(2000);
        waiter.get().interrupt();


        new ReentrantLock().newCondition().await();
    }



}

final class MySync extends AbstractQueuedSynchronizer {

    @Override
    protected boolean tryAcquire(int acquires) {
        if (acquires == 1){
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;

            }
        }
        return false;
    }

    @Override
    protected boolean tryRelease(int acquires) {
        if(acquires == 1) {
            if(getState() == 0) {
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }
        return false;
    }

    protected Condition newCondition() {
        return new ConditionObject();
    }

    @Override
    protected boolean isHeldExclusively() {
        return getState() == 1;
    }

}

